<template>
  <div class="page payParamSettings">
    <div class="scroll-view">
      <StoreChoice
        ref="StoreChoice"
        :current="currentChecked"
        :multipleChoice="true"
        @listenToStoreSelect="getSelectStoreValue"
        :statusFilter="true"
        :hasTotal="true"
        :multipleSelectAll="false"
        :noneCheck="false"
        v-if="role=='1'&&shopCount>1"
        reqUrl="/newapp/shop/getHuabeiShopSelect.do"
        :sourceData="sourceData"
      />
      <customHeader middleTitle="参数设置" @leftCallBack="handleBack" />
      <div class="page-body">
        <ul class="form-ul">
          <li>
            <span>花呗分期</span>
            <div v-if="role=='1'&&shopCount>1" @click="handleClickSelectStore">
              <span v-if="shopId.length>0">已选{{shopId.length}}家门店开启</span>
              <span v-else>请选择</span>
              <i class="zhk-list_rarrow"></i>
            </div>
            <div v-else>
              <mt-switch v-if="inited" v-model="switchValue" @change="handleSwitch"></mt-switch>
            </div>
          </li>
          <div class="sub-text">开启后，支付时订单大于100元可选择使用花呗分期</div>
        </ul>
        <!-- <ul class="form-ul" v-if="role=='1'">
          <li>
            <span>默认使用分期</span>
            <div>
              <mt-switch
                v-model="switchValueHb"
                @change="(v)=>{handleSwitch2(v,'HUABEI_FENQI','switchValueHb')}"
              ></mt-switch>
            </div>
          </li>
          <div class="sub-text">本开关仅适用于开通花呗分期的门店</div>
          <div class="sub-text">开启后，顾客到店消费默认使用分期，也可以自行关闭不使用</div>
        </ul> -->
        <div class="kb-shop" @click="linkToAlipay" v-if="hasKbShop">
          <span>
            <i class="zhk-ts"></i>该功能需商家支付宝签约，若已签约请忽略
          </span>
          <div>
            <span>立即签约</span>
            <i class="zhk-list_rarrow"></i>
          </div>
        </div>
        <ul class="form-ul" v-if="isBuy">
          <li>
            <span>收银台引导成为手机号会员</span>
            <div>
              <mt-switch
                v-model="switchValueCashGuid"
                @change="(v)=>{handleSwitch2(v,'CASH_GUIDE_MOBILE_MEMBER_TWO','switchValueCashGuid')}"
              ></mt-switch>
            </div>
          </li>
          <div class="sub-text">
            开启后，消费者扫码输入消费金额后点击付款按钮时将弹出弹窗引导成为手机号会员
            <!-- <span class="link" @click="preview">点击预览</span> -->
          </div>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue';
import customHeader from '../../components/header/header';
import StoreChoice from "../../components/StoreChoice/StoreChoice";
import { Toast, Switch } from 'mint-ui';
import jsBridge from '../../tools/jsBridge.js';
Vue.component(Switch.name, Switch);
export default {
  name: 'payParamSettings',
  data() {
    return {
      switchValue: false,//花呗分期
      switchValueCashGuid: false,//收银台引导成为手机号会员
      switchValueHb: false, //默认是否使用分期
      role: "",
      shopId: [],
      currentChecked: [],
      shopCount: 0,
      shopList: [],
      loadding: false,//提交中
      inited: false,//初始化完成
      sourceData: {},//传给门店筛选组件的数据
      kbShop: [],//口碑门店,
      hasKbShop: false,
      isBuy:false,//是否订购过营销高级套餐
    };
  },
  methods: {
    handleBack() {
      if (this.$refs.StoreChoice && this.$refs.StoreChoice.popupVisible) {
        this.$refs.StoreChoice.back();
      } else {
        if (String(this.$route.query.close) == 'true') {
          jsBridge.closeWindow();
        } else {
          this.$router.back();
        }
      }
    },
    //打开门店选择
    handleClickSelectStore() {
      this.$refs.StoreChoice.popupShow();
    },
    //门店选择回调
    getSelectStoreValue(value, storeName) {
      let shopId = [];
      value.map((item) => {
        shopId.push(item.selectKey);
      });
      this.shopId = shopId;
      const param = this.formateReqParm(shopId);
      this.openReq(param);
    },
    //开关回调
    handleSwitch(v) {
      if (!this.shopList.length) {
        Toast('未获取到门店');
        return;
      }
      let param = [];
      let status = "";
      if (this.switchValue) {
        status = "1_3";
      } else {
        status = "1_0";
      }
      param.push({ shopId: this.shopList[0], status: status });
      this.openReq(param);
    },
    //请求
    openReq(param) {
      const url = "/newapp/shop/changeHuaBeiShopStatus.do";
      this.ajax({
        url: url,
        type: "post",
        data: { huabeiParams: param },
        controlLoading: false
      })
        .then(res => {
          if (res.success) {
            const checkedShop = param.filter((item) => { return item.status === "1_3" });
            this.setkbFlag(checkedShop);
          } else {
            Toast(res.msg);
          }
        })
        .catch(function (err) {

        });
    },
    //获取门店信息（只有一个门店老板或者是店长，则不显示门店列表直接用开关）
    getShopData() {
      if (this.loadding) {
        return;
      }
      this.loadding = true;

      const url = "/newapp/shop/getHuabeiShopSelect.do";
      this.ajax({
        url: url,
        type: "get",
        controlLoading: false
      })
        .then(res => {
          this.loadding = false;
          if (res.success) {
            const data = res.resultObject;
            this.sourceData = data;
            this.checkDataSource(data);
            this.inited = true;
          }
        })
        .catch((err) => {
          this.loadding = false;
        });
    },
    checkDataSource(data) {
      let shopList = [];
      let currentChecked = [];
      let kbShop = [];
      if (data != null && JSON.stringify(data) != "{}") {
        for (var cityName in data) {
          var childrenList = [];
          if (data[cityName] != null && data[cityName].length > 0) {
            for (var i = 0; i < data[cityName].length; i++) {
              //状态筛选 审批中：1  审批驳回：3  的门店不显示
              if (data[cityName][i].auditStatus !== 1 && data[cityName][i].auditStatus !== 3) {
                shopList.push(data[cityName][i].shopId);

                //花呗开通状态(1:已开通；0：未开通)
                if (data[cityName][i]['huabeiStatus'] === "1_3") {
                  currentChecked.push({ selectKey: data[cityName][i].shopId });
                }
              }
              if (data[cityName][i] && data[cityName][i].isOnline === "T") {
                kbShop.push(data[cityName][i].shopId);
              }
            }
          }
        }
      }
      this.kbShop = [];
      this.hasKbShop = false;
      this.shopList = [];
      this.shopId = [];
      this.currentChecked = [];
      this.hasKbShop = false;
      this.switchValue = false;

      this.kbShop = kbShop;
      this.shopList = shopList;
      this.shopCount = shopList.length;
      this.currentChecked = currentChecked;
      if (currentChecked.length === 1) {
        this.switchValue = true;
      }
      // if (shopList.length < 2) {
      //   this.shopId = shopList;
      // }
      currentChecked.map((item) => {
        this.shopId.push(item.selectKey);
      });


      for (var i = 0; i < currentChecked.length; i++) {
        for (var j = 0; j < kbShop.length; j++) {
          if (currentChecked[i] && currentChecked[i].selectKey === kbShop[j]) {
            this.hasKbShop = true;
          }
        }
      }
    },
    formateReqParm(checkedList) {
      let param = [];
      for (const shopId of this.shopList) {
        let status = "1_0";
        for (const checkedShopId of checkedList) {
          if (shopId === checkedShopId) {
            status = "1_3";
            break;
          }
        }
        param.push({ shopId: shopId, status: status });
      }
      return param;

    },
    linkToAlipay() {
      AppUtil.call(AppUtil.APIS.OPEN_APP, { url: "alipays://platformapi/startapp?appId=20000067&url=https://b.alipay.com/signing/productDetail.htm?productId=J1010300191000001000" }, function (result) {
        if (result.success == 'false') {
          Toast('检测到您尚未安装支付宝，请安装支付宝');
        }
      });
    },
    //是否选中口碑门店
    setkbFlag(currentChecked) {
      this.hasKbShop = false;
      const kbShop = this.kbShop;
      if (kbShop.length === 0) {
        return;
      }
      for (var i = 0; i < currentChecked.length; i++) {
        for (var j = 0; j < kbShop.length; j++) {
          if (currentChecked[i] && currentChecked[i].shopId === kbShop[j]) {
            this.hasKbShop = true;
          }
        }
      }
    },
    //开启关闭
    handleSwitch2(v, functionId, model) {
      let param = [];
      let status = 0;
      if (this[model]) {
        status = 1;
      }
      const url = `/newapp/setting/setFunctionSwitch.do?functionId=${functionId}&state=${status}`;
      this.ajax({
        url: url,
        type: "get",
        controlLoading: false
      })
        .then(res => {
          if (res.success) {
          } else {
            this[model] = !this[model];
            Toast(res.msg);
          }
        })
        .catch((err) => {

        });
    },
    //查询开关状态
    queryFunctionState() {
      const url = "/newapp/setting/queryFunctionState.do";
      this.ajax({
        url: url,
        type: "get",
        controlLoading: false
      })
        .then(res => {
          if (res.success) {
            let hb = false;
            let cash = false;
            let isBuy = false;//是否订购营销高级套餐
            if (res.resultObject && res.resultObject.length > 0) {
              for (const item of res.resultObject) {
                if (item['fmId'] == "CASH_GUIDE_MOBILE_MEMBER_TWO" && item['fmStatus'] == 1) {
                  cash = true;
                }
                if (item['fmId'] == "HUABEI_FENQI" && item['fmStatus'] == 1) {
                  hb = true;
                }
                if (item['fmId'] == "MARKETING_SERVICE" && item['fmStatus'] == 1) {
                  isBuy = true;
                }
              }
            }
            this.switchValueHb = hb;
            this.switchValueCashGuid = cash;
            this.isBuy = isBuy;
          } else {
            Toast(res.msg);
          }
        })
        .catch((err) => {

        });
    },
    preview() {
      this.$router.push({ path: '/fxActivityRecord/list/fxSettings/preview', query: { url: "2019/12/17/15/695671576567197.jpg" } });
    }
  },
  components: {
    customHeader,
    StoreChoice
  },
  created() {
    CommonUtil.getUserInfo().then(data => {
      this.role = data.role;
    });
    this.getShopData();
    this.queryFunctionState();
  },
};
</script>
<style lang='scss' scoped>
@import "payParamSettings";
</style>
<style lang="scss">
.payParamSettings {
	.mint-switch-input:checked + .mint-switch-core {
		background-color: #ff3d33;
		border-color: #ff3d33;
	}
}
</style>
